"use client";

import { Record } from "@/util/type";
import { useAuth } from "@clerk/nextjs";
import axios from "axios";
import {
  Card,
  CardHeader,
  CardBody,
  Image,
  Avatar,
  Divider,
  CardFooter,
  RadioGroup,
  Radio,
  cn,
  Button,
  Progress,
  Modal,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  useDisclosure,
} from "@nextui-org/react";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
interface Props {
  id?: string;
  avatar?: string;
  userId?: string;
  content?: string;
  images?: string[];
  options: Array<{ key: string; value: number }>;
  onDeleteSuccess?: () => void; // 添加这个回调函数
}
import React from "react";

function TicketTopic(props: Props) {
  const [count, setCount] = useState(
    props.options.reduce((acc, item) => acc + item.value, 0)
  );

  const [selectedChoice, setSelectedChoice] = useState("");

  const [isVote, setIsVote] = useState(false);
  const [record, setRecord] = useState<Record>();
  const [options, setOptions] = useState<typeof props.options>(props.options);

  const { userId } = useAuth();
  const { isOpen, onOpen, onOpenChange } = useDisclosure();
  useEffect(() => {
    const fetchIsVote = async () => {
      try {
        // 使用axios发送GET请求
        const result = await axios.get(
          `${process.env.API_ADDRESS}/topic/record?userId=${userId}&topicId=${props.id}`,
          {
            // 配置项可以放在这里，如果需要的话
          }
        );

        // 检查响应状态码
        if (result.status === 200) {
          const data = result.data; // 从axios响应中获取数据
          const record = data.record as Record;
          setIsVote(true);
          setRecord(record);
          setSelectedChoice(record.choice);
        }
      } catch (error) {
        // 处理错误
        console.error("Error fetching data:", error);
      }
    };

    fetchIsVote();
  }, [props.id, userId]);
  const handleDelete = async (onClose: () => void) => {
    try {
      // 发送 DELETE 请求，注意移除了不必要的 Content-Type 头
      const response = await axios.delete(
        process.env.API_ADDRESS + `/topic?id=${props.id}`
      );

      // 检查响应状态码
      if (response.status === 200) {
        toast.success("🦄 删除成功");
        props.onDeleteSuccess?.(); // 调用回调函数
        onClose();
      } else {
        // 对非 200 状态码进行适当处理
        console.error("非 200 响应:", response);
        toast.error("🦄 删除失败");
      }
    } catch (error) {
      // 捕获请求过程中的错误
      console.error("请求过程中的错误:", error);
      toast.error("🦄 删除失败:" + error);
    }

    console.log("删除操作被触发");
  };
  const handleEdit = async () => {
    // 实现编辑逻辑
    console.log("编辑操作被触发");
    // 例如，你可以打开一个模态框来编辑内容
  };

  return (
    <>
      <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1">提示:</ModalHeader>
              <ModalBody>
                <p>确定删除这个话题吗？</p>
              </ModalBody>
              <ModalFooter>
                <Button color="danger" variant="light" onPress={onClose}>
                  取消
                </Button>
                <Button
                  color="primary"
                  onPress={() => {
                    handleDelete(onClose);
                  }}
                >
                  确定
                </Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
      <div className="w-10/12">
        <Card>
          <CardHeader className="pb-0 pt-2 px-4 flex-col items-start">
            <Avatar src={props.avatar} />
            <h4 className="text-lg font-bold">投票内容：</h4>
            <p className="text-tiny font-semibold">{props.content}</p>
          </CardHeader>
          <CardBody className="overflow-visible py-2">
            {props.images &&
              props.images.map((image, index) => (
                <Image
                  key={index}
                  alt="Card image"
                  className="object-cover rounded-xl my-1"
                  src={image}
                  width={270}
                />
              ))}
          </CardBody>
          <CardFooter className="px-4 py-2 flex flex-col justify-center">
            <RadioGroup
              orientation="horizontal"
              value={selectedChoice}
              onValueChange={async (value) => {
                const newOptions = options.map((item) => {
                  if (item.key === value) {
                    return {
                      key: item.key,
                      value: item.value + 1,
                    };
                  }
                  if (item.key === selectedChoice) {
                    return {
                      key: item.key,
                      value: item.value - 1,
                    };
                  }
                  return item;
                });
                setOptions(newOptions);
                if (selectedChoice === "") setCount(count + 1);
                setSelectedChoice(value);
                try {
                  // 使用axios发送POST请求
                  const result = await axios.post(
                    `${process.env.API_ADDRESS}/topic/record`,
                    {
                      topicId: props.id,
                      userId: userId,
                      choice: value,
                    },
                    {
                      headers: {
                        "Content-Type": "application/json",
                      },
                    }
                  );

                  // 检查响应状态码
                  if (result.status === 200) {
                    toast.success("🦄 投票成功");
                    setIsVote(true);
                  }
                } catch (error) {
                  // 处理错误
                  toast.error("🦄 投票异常" + error);
                  console.error("Error posting data:", error);
                }
              }}
            >
              {props.options.map((item) => {
                return (
                  <Radio
                    key={item.key}
                    value={item.key}
                    className={cn(
                      "inline-flex m-0 bg-content1 hover:bg-content2 items-center justify-between",
                      "flex-row-reverse max-w-[300px] cursor-pointer rounded-lg gap-4 p-4 border-2 border-transparent",
                      "data-[selected=true]:border-primary"
                    )}
                  >
                    {item.key}
                  </Radio>
                );
              })}
            </RadioGroup>

            {isVote &&
              options.map((item) => {
                return (
                  <Progress
                    key={item.key}
                    size="sm"
                    radius="sm"
                    classNames={{
                      base: "max-w-md",
                      track: "drop-shadow-md border border-default",
                      indicator: "bg-gradient-to-r from-pink-500 to-yellow-500",
                      label: "tracking-wider font-medium text-default-600",
                      value: "text-foreground/60",
                    }}
                    label={item.key}
                    value={count === 0 ? 0 : (item.value / count) * 100}
                    showValueLabel={true}
                  />
                );
              })}

            <div className="button-container">
              <Button onPress={onOpen} color="primary">
                删除
              </Button>
              <Button
                onClick={handleEdit}
                color="secondary"
                className="ml-2 mt-2"
              >
                编辑投票
              </Button>
            </div>
          </CardFooter>
        </Card>
      </div>
      <Divider className="my-4" />
    </>
  );
}

export default TicketTopic;
